package com.violet.myorm.core.foreign;

import com.violet.myorm.core.condition.LambdaWhere;
import com.violet.myorm.core.execute.Query;

import java.util.List;

public final class Foreign<E>
    implements Relation<E>
{
    private final Class<E> clazz;
    private final String foreign;
    private final Object key;

    private int onload;
    private E e;

    private Foreign(Class<E> clazz, String foreign, Object key, boolean lazy) {
        this.clazz = clazz;
        this.foreign = foreign;
        this.key = key;

        if (!lazy) load();
    }

    private void load() {
        if (onload == 0) {
            List<E> query = new Query<E>(clazz).where(new LambdaWhere().eq(foreign, key)).executeQuery();
            if (!query.isEmpty()) e = query.get(0);
            onload++;
        }
    }

    @Override
    public E getData() {
        if (e == null) load();
        return e;
    }
}
